/**
 *    Copyright 2012 Geensoft S.A.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
package ar.com.greensoft.neo.web.jsf.beans.common;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import ar.com.greensoft.neo.dao.DaoException;
import ar.com.greensoft.neo.dao.UserDao;
import ar.com.greensoft.neo.model.GroupMember;
import ar.com.greensoft.neo.model.MenuAccess;
import ar.com.greensoft.neo.model.User;
import ar.com.greensoft.neo.util.ApplicationRoles;
import ar.com.greensoft.neo.web.jsf.util.HttpJSFUtil;
import ar.com.greensoft.neo.web.jsf.util.JSFMenuUtil;

/**
 * @author Jorge E. Villaverde
 * @date 08/07/2011
 * @version 1.0.0
 */
@Component
@SessionScoped
@ManagedBean
public class HomeBean {
	private static final String HOME_PATH = "home.jsf";
	private static final String ADMIN_HOME_PATH = "admin/" + HOME_PATH;
	private static final String USER_HOME_PATH = "user/" + HOME_PATH;
	private static final String LOGIN_PAGE = "login.jsf";

	private static final Logger logger = LoggerFactory.getLogger(HomeBean.class);
	
	private static Map<String, String> authorityHomeMap;

	
	@Autowired
	private List<ApplicationMenu> userMenues;
	@Autowired
	private UserDao userDao;
	
	static{
		authorityHomeMap = new WeakHashMap<String, String>();
		authorityHomeMap.put(ApplicationRoles.ROLE_ANONYMOUS.name(), LOGIN_PAGE);
		authorityHomeMap.put(ApplicationRoles.ROLE_ADMIN.name(), ADMIN_HOME_PATH);
		authorityHomeMap.put(ApplicationRoles.ROLE_USER.name(), USER_HOME_PATH);
	}
	
	public String getUserHome(){
		if(logger.isTraceEnabled())
			logger.trace("Requesting home");
		
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		
		if(auth == null)
			return LOGIN_PAGE;
		
		for(GrantedAuthority ga : auth.getAuthorities()){
			String homePage = authorityHomeMap.get(ga.getAuthority());
			if(StringUtils.hasLength(homePage))
				return homePage;
		}
		
		return HOME_PATH;
	}	

	public String logout(){
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if(logger.isTraceEnabled())
			logger.trace("Logout: " + auth.getName());
		
		
		if (auth != null){    
			HttpServletRequest request = HttpJSFUtil.getRequest();
			HttpServletResponse response = HttpJSFUtil.getResponse();
			new SecurityContextLogoutHandler().logout(request, response, auth);
			//new PersistentTokenBasedRememberMeServices().logout(request, response, auth);
		}
		return LOGIN_PAGE + JSFMenuUtil.JSF_REDIRECT;
	}
	
	public String getLoggedUsername(){
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if(auth != null)
			return auth.getName();
		return "";
	}


	public String getUserRole() {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();		
		if(auth != null){
			for(GrantedAuthority ga : auth.getAuthorities()){
				String roleName = ga.getAuthority();
				if(StringUtils.hasLength(roleName))
					return roleName;
			}
		}
		return "";
	}
	
	public List<ApplicationMenu> getUserMenues(){
		List<ApplicationMenu> ret = new ArrayList<ApplicationMenu>();
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		try {
			User user = userDao.findById(auth.getName());
			for(GroupMember gm : user.getGroups()){
				for(MenuAccess ma : gm.getGroup().getMenuAccess()){
					ApplicationMenu menu = findAplicationMenu(ma.getName());
					ret.add(menu);
				}
			}
		} catch (DaoException e) {
		}
		
		return ret;
	}

	private ApplicationMenu findAplicationMenu(String name) {
		for(ApplicationMenu menu : userMenues)
			if(menu.getMenuName().equals(name))
				return menu;
		return null;
	}
	
}
